<template>
  <div :v-loading="loading">
    <el-row>
      <el-col :span="6">
        <div v-for="node in data" :key="node.id" style="margin-top: 10px">
          <el-avatar> {{node.name?node.name.substr(0,1):node.id.substr(0,1)}}</el-avatar>
          <span class="node" @click="editNode(node)"
            :title="node.name?node.name:node.id">{{node.name?node.name:node.id.substr(0,10)}}</span>
        </div>
      </el-col>
      <el-col :span="16">
        <el-form v-loading="loading" :model="dataForm" ref="dataForm"
          :label-width="$i18n.locale === 'en-US' ? '140px' : '140px'">
          <el-form-item prop="name" :label="$t('process.task.name')">
            <span v-if="dataForm.taskDefId">
              <el-tag v-if="dataForm.taskName">{{dataForm.taskName}}</el-tag>----<el-tag>{{dataForm.taskDefId}}</el-tag>
            </span>
          </el-form-item>
          <el-form-item prop="type" :label="$t('process.task.type')">
            <el-radio-group size="small" v-model="dataForm.type">
              <el-radio-button label="users">用户</el-radio-button>
              <el-radio-button label="groups">群组</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="dataForm.type ==='users'" prop="users" :label="$t('process.task.userType')">
            <!--下拉框-->
            <el-select v-model="dataForm.userType" :placeholder="$t('process.task.userType')" clearable>
              <el-option v-for="template in $getDictList('FLOW_USER_TYPE', true)" :key="template.val"
                :label="template.label" :value="template.val"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="dataForm.type ==='users' && dataForm.userType === 'user_custom'" prop="users"
            :label="$t('process.task.userCustomDefType')">
            <!--下拉框-->
            <el-select v-model="dataForm.userCustomDefType" :placeholder="$t('process.task.userCustomDefType')"
              filterable remote reserve-keyword clearable :remote-method="getDefTypeList">
              <el-option v-for="item in userCustomDefTypeList" :key="item.defType" :label="item.defName"
                :value="item.defType">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="dataForm.type ==='users' && dataForm.userType === 'user_normal'" prop="users"
            :label="$t('process.task.users')">
            <el-row>
              <el-col :span="20">
                <span v-if="dataForm.users.length<=0"> &nbsp;</span>
                <el-tag v-for="(tag, i) in dataForm.users" :key="i" closable type="info" @close="usersHandleClose(tag)">
                  {{tag.username}}
                </el-tag>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-search" circle @click="showUserSel()"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dataForm.type ==='groups'" prop="depts" :label="$t('process.task.depts')">
            <el-row>
              <el-col :span="20">
                <span v-if="dataForm.depts.length<=0">&nbsp;</span>
                <el-tag v-for="(tag, i) in dataForm.depts" :key="i" closable type="info"
                  @close="deptsHandleClose(tag.id)">
                  {{tag.name}}
                </el-tag>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-search" circle @click="showDeptsSel()"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dataForm.isMultiInstancehas" prop="parallelPersons"
            :label="$t('process.task.parallelPersons')">
            <el-row>
              <el-col :span="10">
                <!--下拉框-->
                <el-select v-model="dataForm.parallelPersonType" :placeholder="$t('process.task.parallelPersonType')"
                  clearable>
                  <el-option v-for="template in $getDictList('FLOW_MULINST_PERSON_TYPE', true)" :key="template.val"
                    :label="template.label" :value="template.val"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-input-number v-if="dataForm.parallelPersonType === '0'" :min="1" :max="20"
                  v-model="dataForm.parallelPersonNums"></el-input-number>
                <el-input v-if="dataForm.parallelPersonType === '1'"
                  :placeholder="$t('process.task.parallelPersonParams')" maxlength="20" show-word-limit
                  v-model="dataForm.parallelPersonParams"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dataForm.isMultiInstancehas" prop="parallelType" :label="$t('process.task.parallelType')">
            <el-row>
              <el-col :span="10">
                <!--下拉框-->
                <el-select v-model="dataForm.parallelType" :placeholder="$t('process.task.parallelType')" clearable>
                  <el-option v-for="template in $getDictList('FLOW_MULINST_TYPE', true)" :key="template.val"
                    :label="template.label" :value="template.val"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-input v-if="dataForm.parallelType === '1'" maxlength="4" show-word-limit v-model="dataForm.ratio">
                </el-input>
                <el-input v-if="dataForm.parallelType === '0'" :placeholder="$t('process.task.keyPeople')"
                  v-model="dataForm.keyPeople"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="dataForm.isMultiInstancehas" label="允许加签" prop="delivery">
            <el-switch v-model="dataForm.signature"></el-switch>
          </el-form-item>
          <el-form-item label="允许转办" prop="delivery">
            <el-switch v-model="dataForm.transfer"></el-switch>
          </el-form-item>
          <el-form-item v-if="!dataForm.isMultiInstancehas" label="自动审批" prop="delivery">
            <el-switch v-model="dataForm.autoApproval"></el-switch>
          </el-form-item>

          <el-form-item v-if="dataForm.type ==='groups'" prop="roles" :label="$t('process.task.roles')">
            <el-select style="width: 95%" v-model="dataForm.roles" value-key="id" multiple>
              <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="dataFormSubmitHandle()">{{ $t('save') }}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <uni-tree-dialog v-if="dialogVisible" ref="treeSelectDept" :styles="{width:'30%'}" :treeParams="treeParams"
      @backFun="deptsBackFun" :data="deptList" @searchFun="deptsSearch"></uni-tree-dialog>
    <uni-user-select v-if="dialogVisible" ref="userSelect" @backFun="userBackFun" :width="'70%'"
      :initDataForm="initDataForm"></uni-user-select>
  </div>
</template>
<script>
const _dataForm = {
  id: '',
  processInstId: '',
  taskDefId: '',
  taskName: '',
  type: 'users',
  relationStr: '',
  remark: '',
  creator: '',
  createDate: '',
  updater: '',
  updateDate: '',
  users: [],
  userType: 'user_normal',
  userCustomDefType: '',
  depts: [],
  roles: [],
  posts: [],
  groups: [],
  parallelType: '',
  isMultiInstancehas: false,
  ratio: '',
  keyPeople: '',
  parallelPersonType: '0',
  signature: false,
  autoApproval: false,
  transfer: false,
  parallelPersonNums: 1,
  parallelPersonParams: '',
  modelKey: ''
}
export default {
  data () {
    return {
      loading: false,
      visible: false,
      dialogVisible: false,
      initDataForm: {},
      id: '',
      modelKey: '',
      data: [],
      roleList: [],
      deptList: [],
      userCustomDefTypeList: [],
      treeParams: {
        title: '选择部门',
        filterable: false,
        clickParent: true,
        multiple: true,
        props: {
          children: 'children',
          label: 'name',
          value: 'id',
          disabled: 'disabled'
        }
      },
      dataForm: {
        ..._dataForm
      }
    }
  },
  methods: {
    init () {
      this.loading = true
      this.dataForm = {
        ..._dataForm
      }
      this.dataForm.processInstId = this.id
      this.dataForm.modelKey = this.modelKey
      console.log('dataForm', this.dataForm)

      Promise.all([
        this.getRoleList(),
        this.getDeptList(),
        this.getDefTypeList('')
      ]).then(() => {
        this.clear()
        this.getTree()
      })
    },
    getDefTypeList (query) {
      return this.$http
        .get('/bpm/bpmTaskExtUser/list', {
          params: {
            defType: query
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.userCustomDefTypeList = res.data
        })
        .catch(() => { })
    },
    // 获取部门列表
    getDeptList () {
      return this.$http
        .get('/sys/dept/list')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.deptList = this.$utils.treeDataTranslate(res.data)
          this.deptList.push({ id: '-1', name: '发起人部门' })
        })
        .catch(() => { })
    },
    // 获取角色列表
    getRoleList () {
      return this.$http
        .get('/sys/role/roleList', { params: { roleGrade: '0' } })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.roleList = res.data
        })
        .catch(() => { })
    },
    getTree () {
      this.$http
        .get('/act/process/nodeList/' + this.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          if (!res.data || res.data.length <= 0) {
            this.$message.info('没有用户节点信息')
            return false
          } else {
            this.data = res.data
          }
          this.loading = false
        })
        .catch(() => { })
    },
    clear () {
      this.$refs['dataForm'].resetFields()
      this.dataForm.users = []
      this.dataForm.depts = []
      this.dataForm.roles = []
    },
    editNode (node) {
      this.loading = true
      this.dataForm.processInstId = this.id
      this.dataForm.taskDefId = node.id
      this.dataForm.taskName = node.name
      this.clear()
      this.getModelRelation()
    },
    getModelRelation () {
      this.$http
        .post('/flowable/bpmTaskExt/getByTaskDefId', {
          processInstId: this.dataForm.processInstId,
          modelKey: this.dataForm.modelKey,
          taskDefId: this.dataForm.taskDefId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          let {
            taskName,
            taskDefId,
            processInstId,
            modelKey,
            ..._data
          } = res.data
          this.dataForm = {
            ...this.dataForm,
            ..._data
          }
          this.loading = false
          if (this.dataForm.type && res.data.relations) {
            let relations = res.data.relations
            let type = this.dataForm.type
            if (type === 'users' && relations.users.length > 0) {
              this.dataForm.users = relations.users
              this.dataForm.userType = res.data.userType
              if (this.$refs.userSelect) {
                this.$refs.userSelect.dataListSelections = relations.users
              }
            } else if (type === 'groups') {
              if (relations.roles.length > 0) {
                relations.roles.forEach(role => {
                  this.dataForm.roles.push(role.id)
                })
              }
              if (relations.depts.length > 0) {
                this.dataForm.depts = relations.depts
                if (this.$refs.treeSelectDept) {
                  relations.depts.forEach(dept => {
                    if (
                      this.$refs.treeSelectDept &&
                      this.$refs.treeSelectDept.$refs.tree
                    ) {
                      this.$refs.treeSelectDept.$refs.tree.setChecked(
                        dept.id,
                        true,
                        false
                      )
                    }
                  })
                }
              }
            }
          } else {
            this.dataForm.type = 'users'
          }
        })
        .catch(() => { })
    },
    usersHandleClose (user) {
      this.dataForm.users = this.dataForm.users.filter(
        item => item.id !== user.id
      )
      this.$refs.userSelect.handleClose(user)
    },
    deptsHandleClose (deptId) {
      this.dataForm.depts = this.dataForm.depts.filter(
        item => item.id !== deptId
      )
      if (this.$refs.treeSelectDept) {
        this.$refs.treeSelectDept.$refs.tree.setChecked(deptId, false, false)
      }
    },
    showDeptsSel () {
      if (!this.dataForm.taskDefId) {
        return this.$message.error('请先选择节点信息')
      }
      this.dialogVisible = true
      // 等待DOM完成更新 v-if 渲染后执行
      this.$nextTick(() => {
        this.$refs.visible = true
        this.$refs.treeSelectDept.init()
      })
    },
    deptsSearch (keywords) {
      this.$refs.treeSelectDept.$refs.tree.filter(keywords)
    },
    showUserSel () {
      if (!this.dataForm.taskDefId) {
        return this.$message.error('请先选择节点信息')
      }
      this.dialogVisible = true
      // 等待DOM完成更新 v-if 渲染后执行
      this.$nextTick(() => {
        this.$refs.userSelect.defaultValues = this.dataForm.users || []
        this.$refs.userSelect.init()
      })
    },
    userBackFun (data) {
      this.dataForm.users = data
    },
    deptsBackFun (data) {
      this.dataForm.depts = data
    },
    dataFormSubmitHandle () {
      if (!this.dataForm.taskDefId) {
        return this.$message.error('请先选择节点信息')
      }
      if (this.dataForm.isMultiInstancehas) {
        if (!this.dataForm.parallelType) {
          return this.$message.error('多实例节点，决策类型不能为空')
        } else {
          if (this.dataForm.parallelType === '1') {
            if (!this.dataForm.ratio) {
              return this.$message.error('决策类型为按成员比例时，比例不能为空')
            }
          } else {
            this.dataForm.ratio = 0.9
            if (!this.dataForm.keyPeople) {
              return this.$message.error('决策类型为关键人时，关键人不能为空')
            }
          }
        }
        if (!this.dataForm.parallelPersonType) {
          return this.$message.error('多实例节点，会签人员类型不能为空')
        } else {
          if (this.dataForm.parallelPersonType === '1') {
            if (!this.dataForm.parallelPersonParams) {
              return this.$message.error(
                '会签人员类型为自定义变量时，变量内容不能为空'
              )
            }
          }
        }
      }
      this.loading = true
      // 组装数据 关系json串
      let relation = {}
      relation.type = this.dataForm.type
      relation.userType = this.dataForm.userType
      relation.userCustomDefType = this.dataForm.userCustomDefType
      relation.parallelPersonType = this.dataForm.parallelPersonType
      relation.parallelPersonNums = this.dataForm.parallelPersonNums
      relation.parallelPersonParams = this.dataForm.parallelPersonParams
      relation.parallelType = this.dataForm.parallelType
      relation.ratio = this.dataForm.ratio
      relation.keyPeople = this.dataForm.keyPeople
      relation.signature = this.dataForm.signature
      relation.autoApproval = this.dataForm.autoApproval
      relation.transfer = this.dataForm.transfer

      relation.codes = {}
      if (relation.type === 'users') {
        relation.codes.users = []
        this.dataForm.users.forEach(user => {
          let temp = {}
          temp.id = user.id
          temp.username = user.username
          relation.codes.users.push(temp)
        })
      } else if (relation.type === 'groups') {
        relation.codes.depts = []
        this.dataForm.depts.forEach(dept => {
          let temp = {}
          temp.id = dept.id
          temp.name = dept.name
          relation.codes.depts.push(temp)
        })
        relation.codes.roles = []
        this.dataForm.roles.forEach(role => {
          let temp = {}
          temp.id = role
          relation.codes.roles.push(temp)
        })
      } else {
        return this.$message.error('人员类型不识别')
      }
      this.dataForm.relationStr = JSON.stringify(relation)
      // 保存数据
      this.$http[!this.dataForm.id ? 'post' : 'put'](
        'flowable/bpmTaskExt',
        this.dataForm
      )
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.loading = false
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => { }
          })
        })
        .catch(() => { })
    }
  }
}
</script>
<style>
.node {
  display: inline-block;
  margin-left: 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}

.el-avatar {
  background: #5cb85c;
}

.el-dialog__body {
  padding: 10px 20px;
}
</style>
